/*
 *
 *  * | Licensed 未经许可不能去掉「OPENIITA」相关版权
 *  * +----------------------------------------------------------------------
 *  * | Author: xw2sy@163.com
 *  * +----------------------------------------------------------------------
 *
 *  Copyright [2024] [OPENIITA]
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 * /
 */

package cc.iotkit.data.service;

import cc.iotkit.common.api.PageRequest;
import cc.iotkit.common.api.Paging;
import cc.iotkit.common.utils.MapstructUtils;
import cc.iotkit.common.utils.StringUtils;
import cc.iotkit.data.dao.IJPACommData;
import cc.iotkit.data.dao.SysOrderRepository;
import cc.iotkit.data.model.TbSysOrder;
import cc.iotkit.data.model.TbUserInfo;
import cc.iotkit.data.system.ISysOrderData;
import cc.iotkit.data.util.PredicateBuilder;
import cc.iotkit.model.miniAdmin.OrderStatis;
import cc.iotkit.model.system.SysOrder;
import cc.iotkit.model.system.SysUser;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

import static cc.iotkit.data.model.QTbSysOrder.tbSysOrder;

/**
 * @Author：tfd
 * @Date：2023/5/31 9:45
 */
@Primary
@Service
@RequiredArgsConstructor
public class SysOrderDataImpl implements ISysOrderData, IJPACommData<SysOrder, Long> {

    private final SysOrderRepository sysOrderRepository;

    private final JPAQueryFactory jpaQueryFactory;

    @Override
    public JpaRepository getBaseRepository() {
        return sysOrderRepository;
    }

    @Override
    public Class getJpaRepositoryClass() {
        return TbSysOrder.class;
    }

    @Override
    public Class getTClass() {
        return SysOrder.class;
    }

    @Override
    public Paging<SysOrder> findByConditions(PageRequest<SysOrder> pageRequest) {
        SysOrder data = pageRequest.getData();
        Predicate predicate = buildQueryCondition(data);
        QueryResults<TbSysOrder> tbSysOrderQueryResults = jpaQueryFactory.select(tbSysOrder)
                .from(tbSysOrder).where(predicate).offset(pageRequest.getOffset())
                .limit(pageRequest.getPageSize()).fetchResults();

        return new Paging<>(tbSysOrderQueryResults.getTotal(),
                MapstructUtils.convert(tbSysOrderQueryResults.getResults(), SysOrder.class));
    }

    private Predicate buildQueryCondition(SysOrder query) {
        return PredicateBuilder.instance()
                .and(StringUtils.isNotBlank(query.getOrderNo()), ()->
                        tbSysOrder.orderNo.like(query.getOrderNo()))
                .and(StringUtils.isNotBlank(query.getNickname()), ()->
                        tbSysOrder.nickname.eq(query.getNickname()))

                .build();
    }

    @Override
    public Paging<SysOrder> findByConditions(String orderNo, String startTime, String endTime,
                                             Integer offset, Integer pageSize) throws Exception {
        PredicateBuilder predicateBuilder =  PredicateBuilder.instance();

                if(StringUtils.isNotBlank(orderNo)){
                    predicateBuilder.and( tbSysOrder.orderNo.like(orderNo));
                }

                if(StringUtils.isNotBlank(startTime)){

                    Date startDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(startTime);
                    predicateBuilder.and(tbSysOrder.createTime.after(startDateTime));
                }
                if(StringUtils.isNotBlank(endTime)){
                    Date endDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endTime);
                    predicateBuilder.and( tbSysOrder.createTime.before(endDateTime));
                }

        Predicate  predicate =   predicateBuilder.build();

        QueryResults<TbSysOrder> tbSysOrderQueryResults = jpaQueryFactory.select(tbSysOrder)
                .from(tbSysOrder).where(predicate).offset(offset)
                .limit(pageSize).fetchResults();

        return new Paging<>(tbSysOrderQueryResults.getTotal(),
                MapstructUtils.convert(tbSysOrderQueryResults.getResults(), SysOrder.class));
    }

    @Override
    public OrderStatis getCountStatis(String orderNo, String startTime, String endTime, Integer offset, Integer pageSize)
            throws Exception {

        OrderStatis orderStatis = new OrderStatis();

        Paging<SysOrder> page = findByConditions(orderNo,startTime,endTime,offset,pageSize);

        List<SysOrder> orderList =page.getRows();

        // 初始化统计变量
        Integer totalCount = 0;
        Integer validCount = 0;
        Integer unValidCount = 0;
        Integer processingCount = 0;
        Integer refundCount = 0;
        Integer overdueCount = 0;

        BigDecimal totalAmt = BigDecimal.ZERO;
        BigDecimal validAmt = BigDecimal.ZERO;
        BigDecimal unValidAmt = BigDecimal.ZERO;
        BigDecimal processingAmt = BigDecimal.ZERO;
        BigDecimal refundAmt = BigDecimal.ZERO;
        BigDecimal overdueAmt = BigDecimal.ZERO;

        // 遍历订单列表，统计各种状态的订单数量
        for (SysOrder order : orderList) {
            totalCount++; // 总订单数
            totalAmt.add(order.getRealAmount());
            // 根据订单状态更新统计信息
            switch (order.getStatus()) {
                case -1:
                    unValidCount++;
                    unValidAmt.add(order.getRealAmount());
                    break;
                case 3:
                    processingCount++;
                    validCount++;
                    processingAmt.add(order.getRealAmount());
                    validAmt.add(order.getRealAmount());
                    break;
                case 4:
                    refundCount++;
                    validCount++;
                    refundAmt.add(order.getRealAmount());
                    validAmt.add(order.getRealAmount());
                    break;
                case 6:
                    overdueCount++;
                    validCount++;
                    overdueAmt.add(order.getRealAmount());
                    validAmt.add(order.getRealAmount());
                    break;
                default:
                    // 如果有其他状态，可以在这里处理
                    break;
            }
        }

        // 设置统计结果到 OrderStatis 对象
        orderStatis.setTotalCount(totalCount);
        orderStatis.setValidCount(validCount);
        orderStatis.setUnValidCount(unValidCount);
        orderStatis.setProcessingCount(processingCount);
        orderStatis.setRefundCount(refundCount);
        orderStatis.setOverdueCount(overdueCount);

        orderStatis.setTotalAmt(totalAmt);
        orderStatis.setValidAmt(validAmt);
        orderStatis.setUnValidAmt(unValidAmt);
        orderStatis.setProcessingAmt(processingAmt);
        orderStatis.setRefundAmt(refundAmt);
        orderStatis.setOverdueAmt(overdueAmt);


        return orderStatis;
    }


    //    @Override
//    public List<TbSysOrder> findAllByCondition(TbSysOrder data) {
//        List<TbSysOrder> ret=jpaQueryFactory.selectFrom(tbSysOrder).where(PredicateBuilder.instance()
//
//                .and(StringUtils.isNotBlank(data.getOrderNo()),()->tbSysOrder.orderNo.like(data.getOrderNo()))
//
//                .and(StringUtils.isNotBlank(data.getStatus()),()->tbSysOrder.status.eq(data.getStatus()))
//                .build()).fetch();
//        return MapstructUtils.convert(ret, TbSysOrder.class);
//    }
//
//    @Override
//    public TbSysOrder save(TbSysOrder data) {
//        Long id = data.getId();
//        Object tbData = MapstructUtils.convert(data, getJpaRepositoryClass());
//        Optional byId = id == null ? Optional.empty() : getBaseRepository().findById(id);
//        if (byId.isPresent()) {
//            Object dbObj = byId.get();
//            //只更新不为空的字段
//            BeanUtil.copyProperties(tbData, dbObj, CopyOptions.create().ignoreNullValue());
//            tbData = dbObj;
//        }
//
//        Object o = getBaseRepository().save(tbData);
//        return (TbSysOrder) MapstructUtils.convert(o, getTClass());
//    }

}
